package com.nl.controller.sms5g.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.global.GlobalConstants;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.AES;
import com.nl.controller.common.util.BaseResult;
import com.nl.controller.sms5g.bean.bo.SendRangeSynchronizationReq;
import com.nl.controller.sms5g.bean.bo.Sms5gGetStationsReq;
import com.nl.controller.sms5g.bean.po.LongAndLatsInfo;
import com.nl.controller.sms5g.bean.po.SendRangeSynchronizationResp;
import com.nl.controller.sms5g.bean.po.Sms5gGetStationsResp;
import com.nl.controller.sms5g.service.Sms5gRangeStationsService;
import com.nl.controller.web.bean.SmsBaseStation;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.mapper.SmsBaseStationMapper;
import com.nl.controller.web.util.GZipUtil;
import com.nl.controller.web.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @desc 查询范围内基站编码
 * @return null
 * @author l
 * @date 2021/6/7 14:28
 */
@Service
@Slf4j
public class Sms5gRangeStationsServiceImpl implements Sms5gRangeStationsService {

    @Autowired
    private SmsBaseStationMapper smsBaseStationMapper;
    @Override
    public BaseResult<SendRangeSynchronizationResp> qryRangeStations(SendRangeSynchronizationReq req) {
        BaseResult<SendRangeSynchronizationResp> result = BaseResult.newFailInstance();
        Map map = new HashMap();
        String sendRangeSynchronizationUrl = GlobalConstants.SEND_RANGE_SYNCHRONIZATION_URL;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mgrId",req.getMgrId());
        jsonObject.put("longAndLatList",req.getLongAndLatList());
        jsonObject.put("stationIds",req.getStationIds());
        jsonObject.put("checkState",req.getCheckState());
        jsonObject.put("mgrState",req.getMgrState());
        jsonObject.put("streamSeq",req.getStreamSeq());
        log.info("sendRangeSynchronization interface request:"+jsonObject.toJSONString());
        try {
            String resp = CommonService.httpPostWithJson(sendRangeSynchronizationUrl, jsonObject);
            //String resp = "1";
            if (!StringUtils.isEmpty(resp)){
                //解压
                resp = GZipUtil.gunzip(resp);
                log.info("sendRangeSynchronization interface response:"+resp);
                //resp = "{\"resultCode\":\"0\",\"stationIds\":\"Ws2URdk5UWlxeE4vj9MMmg,y7ybSd9uQZw_XsYgABfkJQ\",\"mgrId\":\"1000001961\"}";
                JSONObject respJson=JSONObject.parseObject(resp);
                String resultCode = respJson.getString("resultCode");
                if (GlobalConstants.SUCCESS_STRING.equals(resultCode)){
                    String stationIds = respJson.getString("stationIds");
                    String[] stationArr = stationIds.split(",");

                    //String mgrId = respJson.getString("mgrId");
                    String mgrId = req.getMgrId();
                    int number ;
                    List<String> stationList = Arrays.asList(stationArr);
                    String decryptStationIds = "";
                    if(CollectionUtils.isEmpty(stationList)){
                        number = 0;
                    }else{
                        number = stationArr.length;
                        for(String encryptStationId : stationList){
                            //解密入库
                            String decryptStationId = AES.decrypt(encryptStationId, "HuaDongJieSuo123");
                            if(StringUtils.isEmpty(decryptStationIds)){
                                decryptStationIds = decryptStationId;
                            }else{
                                decryptStationIds = decryptStationIds+","+decryptStationId;
                            }
                        }
                    }

                    //此处基站入库
                    map.put("stationIds",stationIds);
                    map.put("stationCount",number);
                    SendRangeSynchronizationResp sendRangeSynchronizationResp = new SendRangeSynchronizationResp(mgrId,number+"",decryptStationIds);
                    result.setRetCode(GlobalConstants.SUCCESS_STRING);
                    result.setData(sendRangeSynchronizationResp);
                } else {
                    String respMsg = StringUtils.isEmpty(respJson.getString("resultDesc")) ? "IT接口提示：获取基站错误" : respJson.getString("resultDesc");
                    result.setRetMsg(respMsg);
                }
            } else {
                result.setRetMsg("IT接口提示：获取基站返回数据为空");
            }
        } catch (Exception e) {
            result.setRetMsg("IT接口异常："+e.getMessage());
        }
        return result;
    }

    @Override
    public BaseResult<Sms5gGetStationsResp> xuYiGetStations(Sms5gGetStationsReq req) {
        BaseResult<Sms5gGetStationsResp> result = BaseResult.newFailInstance();
        Sms5gGetStationsResp sms5gGetStationsResp = new Sms5gGetStationsResp();
        List<LongAndLatsInfo> longAndLatList = new ArrayList<>();
        String aesStations = "";
        if (!CollectionUtils.isEmpty(req.getLongAndLatList())){
            longAndLatList = getLongAndLatList(req.getLongAndLatList());
        }
        try {
            String mgrId = req.getMgrId();
            SendRangeSynchronizationReq sendRangeSynchronizationReq = new SendRangeSynchronizationReq();
            sendRangeSynchronizationReq.setMgrId(mgrId);
            sendRangeSynchronizationReq.setCheckState("2");
            sendRangeSynchronizationReq.setLongAndLatList(longAndLatList);
            sendRangeSynchronizationReq.setMgrState("2");
            sendRangeSynchronizationReq.setStationIds("");
            sendRangeSynchronizationReq.setStreamSeq("");
            BaseResult<SendRangeSynchronizationResp> baseResult = qryRangeStations(sendRangeSynchronizationReq);
            log.info("==="+baseResult.toString());
            String respStationIds = baseResult.getData().getStationIds();

            sms5gGetStationsResp.setMgrId(req.getMgrId());
            sms5gGetStationsResp.setStationCount(baseResult.getData().getStationCount());

            sms5gGetStationsResp.setStationIds(baseResult.getData().getStationIds());
            result.setRetCode(GlobalConstants.SUCCESS_STRING);
            result.setRetMsg("查询范围基站成功");
            result.setData(sms5gGetStationsResp);


//            //拼接所选区域对应加密的基站编码
//            if (StringUtils.isEmpty(respStationIds)){
//                respStationIds = aesStations;
//            } else {
//                respStationIds = respStationIds + ","+aesStations;
//            }
//            //封装返回参数
//            baseResult.getData().setStationIds(respStationIds);

//
//            if (GlobalConstants.SUCCESS_STRING.equals(baseResult.getRetCode())){
//                SendRangeSynchronizationResp resp = baseResult.getData();
//                Integer stationCount = addStationTemp(resp);
//                Sms5gGetStationsResp data = new Sms5gGetStationsResp(resp.getMgrId(),String.valueOf(stationCount));
//                result.setRetCode(GlobalConstants.SUCCESS_STRING);
//                result.setData(data);
//            } else {
//                result.setRetMsg(baseResult.getRetMsg());
//            }
        }catch (Exception e){
            log.error("Sms5gGetStations get a exception "+ e.toString());
            e.printStackTrace();
        }
        return result;
    }




    private List<LongAndLatsInfo> getLongAndLatList(List<String> latList){
        List<LongAndLatsInfo> longAndLatList = new ArrayList<>();
        try{
            for (String latsInfo: latList) {
                StringBuilder stringBuilder = new StringBuilder();
                String[] split = latsInfo.split("\\+");
                if (split.length==2){
                    String gps = CommonService.BdToGPS(split[0]);
                    stringBuilder.append(gps).append("|").append(split[1]);
                } else {
                    for (int i=0;i<split.length;i++){
                        String gps = CommonService.BdToGPS(split[i]);
                        if (i == split.length-1){
                            stringBuilder.append(gps);
                        } else {
                            stringBuilder.append(gps).append("|");
                        }
                    }
                }
                longAndLatList.add(new LongAndLatsInfo(stringBuilder.toString()));
            }
        } catch (Exception e){
            log.info("获取基站时经纬度转换异常:"+e.getMessage());
            throw new SmsException("获取基站时经纬度转换异常");
        }
        return  longAndLatList;
    }
}
